package com.gxa.community.admin.service.agent.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxa.community.admin.mapper.OperateKillSpellMapper;
import com.gxa.community.admin.mapper.agent.AgentIndexGoodsMapper;
import com.gxa.community.admin.mapper.agent.QueryGoodsTopicKillMapper;
import com.gxa.community.admin.mapper.agent.UserAgentApplicationMapper;
import com.gxa.community.admin.mapper.agent.UserTagsRelMapper;
import com.gxa.community.admin.mapper.order.OrderInfoMapper;
import com.gxa.community.admin.mapper.order.UserInfoMapper;
import com.gxa.community.admin.service.OperateKillSpellService;
import com.gxa.community.admin.service.agent.AgentService;
import com.gxa.community.admin.service.order.OrderService;
import com.gxa.community.admin.service.agent.UserAgentApplicationService;
import com.gxa.community.core.pojo.bo.agent.AgentAppNoAndReason;
import com.gxa.community.core.pojo.domain.*;
import com.gxa.community.core.pojo.domain.OperateKillSpell;
import com.gxa.community.core.pojo.vo.agent.AgentInfoVo;
import com.gxa.community.core.pojo.dto.agent.AgentIndexGoods;
import com.gxa.community.core.pojo.dto.agentindexdto.AgentIndex;
import com.gxa.community.core.pojo.dto.agentindexdto.QueryGoodsTopicKill;
import com.gxa.community.core.pojo.vo.agent.AgentVo;
import com.gxa.community.core.pojo.vo.order.UserInfoVo;
import com.gxa.community.core.utils.CalendarUtils;
import com.gxa.community.core.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotBlank;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AgentServiceImpl implements AgentService {

    final UserAgentApplicationMapper agentMapper;
    final UserInfoMapper userInfoMapper;
    final UserTagsRelMapper tagsMapper;
    final OrderInfoMapper orderInfoMapper;
    final OrderService orderService;
    @Autowired
    private UserAgentApplicationService userAgentApplicationService;
    @Autowired
    private com.gxa.community.admin.mapper.user.UserInfoMapper1 userInfoMapper1;
    @Autowired
    private AgentIndexGoodsMapper agentIndexGoodsMapper;
    @Autowired
    private QueryGoodsTopicKillMapper queryGoodsTopicKillMapper;
    @Autowired
    private OperateKillSpellService secKillService;
    @Autowired
    private OperateKillSpellMapper operateKillSpellMapper;


    public AgentServiceImpl(UserAgentApplicationMapper agentMapper, UserInfoMapper userInfoMapper, UserTagsRelMapper tagsMapper, OrderInfoMapper orderInfoMapper, OrderService orderService) {
        this.agentMapper = agentMapper;
        this.userInfoMapper = userInfoMapper;
        this.tagsMapper = tagsMapper;
        this.orderInfoMapper = orderInfoMapper;
        this.orderService = orderService;
    }

    /**
     * 查询团长申请信息
     */
    @Override
    public R queryApplication(Integer page, Integer size, AgentVo agentVo) {
        Page<UserAgentApplication> infoPage = new Page<>(page, size);


        Set<Integer> userIds = new HashSet<>();
        // 根据个人信息查询团长用户id
        if (StringUtils.isNotBlank(agentVo.getNickName()) || StringUtils.isNotBlank(agentVo.getPhone()))
            userIds = userInfoMapper.selectList(
                    Wrappers.lambdaQuery(UserInfo.class)
                            .select(UserInfo::getUserId)
                            .like(StringUtils.isNotBlank(agentVo.getNickName()), UserInfo::getNickName, agentVo.getNickName())
                            .eq(StringUtils.isNotBlank(agentVo.getPhone()), UserInfo::getPhone, agentVo.getPhone())
            ).stream().map(UserInfo::getUserId).collect(Collectors.toSet());

        // 根据用户标签查询团长用户id
        if (agentVo.getUserTag() != null)
            userIds.addAll(tagsMapper.selectList(
                    Wrappers.lambdaQuery(UserTagsRel.class)
                            .select(UserTagsRel::getUserId)
                            .eq(UserTagsRel::getTags, agentVo.getUserTag())
            ).stream().map(UserTagsRel::getTags).collect(Collectors.toSet()));
        // 团长基础信息
        Page<UserAgentApplication> agentPage = new LambdaQueryChainWrapper<>(agentMapper)
                .like(StringUtils.isNotBlank(agentVo.getPointName()), UserAgentApplication::getIslandName, agentVo.getPointName())
                .like(StringUtils.isNotBlank(agentVo.getPointAddress()), UserAgentApplication::getIslandAddress, agentVo.getPointAddress())
                .eq(agentVo.getPointType() != null, UserAgentApplication::getIslandType, agentVo.getPointType())
                .eq(agentVo.getStatus() != null, UserAgentApplication::getStatus, agentVo.getStatus())
                .in(!userIds.isEmpty(), UserAgentApplication::getUserId, userIds)
                .page(infoPage);

        List<UserAgentApplication> agentInfos = agentPage.getRecords();

        if (agentInfos == null || agentInfos.isEmpty())
            return R.page(agentPage.getCurrent(), agentPage.getSize(), agentPage.getTotal(), new ArrayList<>());

        // 查询团长用户信息
        HashMap<Integer, UserInfoVo> userVos = userInfoMapper.selectList(
                Wrappers.lambdaQuery(UserInfo.class)
                        .in(UserInfo::getUserId, agentInfos.stream().map(UserAgentApplication::getUserId).collect(Collectors.toSet()))
        ).stream().collect(HashMap::new, (map, agent) -> map.put(agent.getUserId(), userToVo(agent)), HashMap::putAll);

        List<AgentInfoVo> agentInfoVos = new ArrayList<>();
        for (UserAgentApplication agentInfo : agentInfos) {
            agentInfoVos.add(new AgentInfoVo()
                    .setUser(userVos.get(agentInfo.getUserId()))
//                    .setApplicationNo(agentInfo.getApplicationNo())
                    .setApplicationTime(agentInfo.getApplicationTime())
                    .setPointName(agentInfo.getIslandName())
                    .setPointAddress(agentInfo.getIslandAddress())
                    .setPointType(agentInfo.getIslandType())
                    .setPointCoordinate(agentInfo.getIslandCoordinate())
                    .setPointIs(agentInfo.getIslandIs())
                    .setPointNo(agentInfo.getIslandNo())
                    .setPointPhone(agentInfo.getIslandPhone())
                    .setStartTime(agentInfo.getIslandStartTime())
                    .setEndTime(agentInfo.getIslandEndTime())
                    .setPointLicense(agentInfo.getIslandLicense())
                    .setPointImg(agentInfo.getIslandImg())
                    .setPointCardFg(agentInfo.getIslandCardFg())
                    .setPointCardBg(agentInfo.getIslandCardBg())
            );
        }

        return R.page(agentPage.getCurrent(), agentPage.getSize(), agentPage.getTotal(), agentInfoVos);
    }

    /**
     * 批量同意团长申请
     */
    @Override
    public R agreeApplication(List<Integer> nos) {
        if (agentMapper.update(new UserAgentApplication().setStatus(1)
                , Wrappers.lambdaUpdate(UserAgentApplication.class)
                        .in(UserAgentApplication::getUserId, nos)
        ) > 0)
            return R.ok();
        return R.error();
    }

    @Override
    public R rejectApplication(AgentAppNoAndReason nos) {
        if (agentMapper.update(new UserAgentApplication().setStatus(-1).setReason(nos.getReason())
                , Wrappers.lambdaUpdate(UserAgentApplication.class)
                        .in(UserAgentApplication::getUserId, nos.getNos())
        ) > 0)
            return R.ok();
        return R.error();
    }

    /**
     * 根据团长id查询订单下的商品信息
     *
     * @param uid     团长id
     * @param orderNo 订单号列表
     */
    @Override
    public R queryGoods(Integer uid, List<String> orderNo) {
        Set<Integer> list = orderInfoMapper.selectList(
                Wrappers.lambdaQuery(OrderInfo.class)
                        .select(OrderInfo::getAgentId)
                        .in(OrderInfo::getNos, orderNo)
        ).stream().map(OrderInfo::getAgentId).collect(Collectors.toSet());

        if (list.size() != 1 || list.toArray()[0] != uid) return R.error("订单号有误");
        return orderService.queryGoods(orderNo);
    }

    @Override
    public R queryAgentIndex(Integer userId) {
        // 获取当天的起始和结尾
        long startToday = CalendarUtils.today();
        long todayLast = CalendarUtils.todaytail();
        //今日订单
        Integer orderCount = orderInfoMapper.queryOrderCount(userId, startToday, todayLast);
        //今日预估佣金
        if (orderCount!=null){ Double commission = orderCount * 0.5;}
        Double commission = orderCount * 0.5;
        //今日下单人数
        Integer peopleCount = orderInfoMapper.queryPeopleCount(userId, startToday, todayLast);
        //团长邀请人数
        Integer people = orderInfoMapper.queryPeople(userId);
        //预计奖励
        if (people!=null){
            Double award = people * 5.0;
        }
        Double award = 0.0;
        //团长地址
        QueryWrapper<UserAgentApplication> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        UserAgentApplication userAgentApplication = agentMapper.selectOne(wrapper);
        System.err.println(userAgentApplication);
        if (userAgentApplication!=null){
            String islandName = userAgentApplication.getIslandName();//团长的自提点地址
            AgentIndex agentIndex = new AgentIndex();
            agentIndex.setAgentLocal(islandName);
            agentIndex.setAward(award);
            agentIndex.setCommission(commission);
            agentIndex.setInvatePeople(people);
            agentIndex.setOrderCount(orderCount);
            agentIndex.setPeopleCount(peopleCount);
            return R.ok().put("data", agentIndex);
        }
        return R.error(306,"没有该团长信息");
    }

    @JmsListener(destination = "shareurl")
    @Override
    public void updateUrl(String url) {
        System.err.println("监听到了"+url);
        String s = org.apache.commons.lang3.StringUtils.substringAfterLast(url, "/");
        Integer integer = userInfoMapper1.updateUrl(Integer.valueOf(s), url);
        System.err.println(integer);
    }

    @Override
    public R wellGoodsShare() {
        //查询好货上新标签下的商品
        QueryWrapper<AgentIndexGoods> wrapper =  new QueryWrapper<>();
        wrapper.eq("tag_name","好货上新");
        wrapper.eq("status",1);
        List<AgentIndexGoods> agentIndexGoods = agentIndexGoodsMapper.selectList(wrapper);
        return R.ok().put("data",agentIndexGoods);
    }

    @Override
    public R todaySeckill() {
        //今天获取当前时间
        long today = CalendarUtils.today();//今日开始时间
        long todaytail = CalendarUtils.todaytail();//今日结束时间
        //先去查询秒杀活动的killId
        QueryWrapper<OperateKillSpell> wrapper =  new QueryWrapper<>();
        wrapper.eq("type",1);
        wrapper.ge("start_time",today);
        wrapper.le("end_time",todaytail);
        wrapper.le("status",0);
        List<OperateKillSpell> operateKillSpells = operateKillSpellMapper.selectList(wrapper);
        List<QueryGoodsTopicKill> queryGoodsTopicKills = new ArrayList<>();
        for (OperateKillSpell operateKillSpell : operateKillSpells) {
            @NotBlank String killId = operateKillSpell.getKillId();
            //根据killid查出商品信息
            QueryWrapper<QueryGoodsTopicKill> killGoodswrapper =  new QueryWrapper<>();
            killGoodswrapper.eq("kill_id",killId);
            List<QueryGoodsTopicKill> queryGoodsTopicKills1 = queryGoodsTopicKillMapper.selectList(killGoodswrapper);
            for (QueryGoodsTopicKill queryGoodsTopicKill : queryGoodsTopicKills1) {
                queryGoodsTopicKills.add(queryGoodsTopicKill);
            }

        }

        return R.ok().put("data",queryGoodsTopicKills);
    }

    @Override
    public R todayGroup() {
        //今天获取当前时间
        long today = CalendarUtils.today();//今日开始时间
        long todaytail = CalendarUtils.todaytail();//今日结束时间
        //先去查询秒杀活动的killId
        QueryWrapper<OperateKillSpell> wrapper =  new QueryWrapper<>();
        wrapper.eq("type",2);
        wrapper.ge("start_time",today);
        wrapper.le("end_time",todaytail);
        wrapper.le("status",0);
        List<OperateKillSpell> operateKillSpells = operateKillSpellMapper.selectList(wrapper);
        List<QueryGoodsTopicKill> queryGoodsTopicKills = new ArrayList<>();
        for (OperateKillSpell operateKillSpell : operateKillSpells) {
            @NotBlank String killId = operateKillSpell.getKillId();
            //根据killid查出商品信息
            QueryWrapper<QueryGoodsTopicKill> killGoodswrapper =  new QueryWrapper<>();
            killGoodswrapper.eq("kill_id",killId);
            List<QueryGoodsTopicKill> queryGoodsTopicKills1 = queryGoodsTopicKillMapper.selectList(killGoodswrapper);
            for (QueryGoodsTopicKill queryGoodsTopicKill : queryGoodsTopicKills1) {
                queryGoodsTopicKills.add(queryGoodsTopicKill);
            }

        }

        return R.ok().put("data",queryGoodsTopicKills);
    }

    private UserInfoVo userToVo(UserInfo agent) {
        return new UserInfoVo()
                .setUserId(agent.getUserId())
                .setNickName(agent.getNickName())
                .setPhone(agent.getPhone());
    }
}
